<template>
  <div class="containers">
    <div class="container">
      <div class="form-box" style="width: 100%;padding: 20px;">
        <el-row>


        <el-form ref="form" :model="form" label-width="100px" :rules="rules">
          <el-col :span="8">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" size="mini" style="width: 220px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品分区" prop="name">
              <el-select v-model="form.partition_id" @change="changeissing" placeholder="请选择商品分区" size="mini"
                class="mr10" style="width: 220px;">
                <el-option v-for="(item, index) in navigation_list" :key="item.ID" :label="item.name"
                  :value="item.ID"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="一级分类" prop="name">
              <el-select v-model="form.class_first_id" @change="setfirst" placeholder="请选择一级分类" size="mini" class="mr10" style="width: 220px;">
                <el-option v-for="(item, index) in firstlist" :key="item.ID" :label="item.name"
                  :value="item.ID"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="二级分类">
              <el-select v-model="form.class_second_id" placeholder="请选择二级分类" size="mini" class="mr10"
                @change="setsecond" style="width: 220px;">
                <el-option v-for="(item, index) in secondlist" :key="item.ID" :label="item.name"
                  :value="item.ID"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运费模版">
              <el-select v-model="form.freight" placeholder="请选择运费模版" size="mini" class="mr10" style="width: 220px;">
                <el-option v-for="(item, index) in options" :key="item.ID" :label="item.name"
                  :value="item.ID"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品价格" prop="name">
              <el-input v-model="form.price" size="mini" placeholder="请输入商品价格" onkeyup="value=value.replace(/[^\d.]/g,'')"
                style="max-width: 220px;"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="商品库存" prop="name">
              <el-input size="mini" v-model="form.stock" onkeyup="value=value.replace(/[^\d]/g,'')" style="max-width: 220px;"
                placeholder="请输入商品库存"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="虚拟销量" prop="name">
              <el-input size="mini" v-model="form.virtually_sales" onkeyup="value=value.replace(/[^\d]/g,'')"
                style="max-width: 220px;" placeholder="请输入商品虚拟销量"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品排序" prop="name">
              <el-input size="mini" v-model="form.sort" onkeyup="value=value.replace(/[^\d]/g,'')" style="max-width: 220px;"
                placeholder="请输入商品排序"></el-input>
            </el-form-item>
          </el-col>


<!--          <el-col :span="8">-->
<!--            <el-form-item label="会员让利" prop="discount">-->
<!--              <div style="display: flex;align-items: center;">-->
<!--                <el-input size="mini" v-model="form.discount" type="number" :max="30"  style="max-width: 220px;"-->
<!--                        placeholder="请输入让利"></el-input>-->
<!--                <div>（⩽30）</div>-->
<!--              </div>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="8">-->
<!--            <el-form-item label="平台让利" prop="platform_discount">-->
<!--              <div style="display: flex;align-items: center;">-->
<!--                <el-input size="mini" v-model="form.platform_discount" type="number" :max="80"  style="max-width: 220px;"-->
<!--                        placeholder="请输入让利"></el-input>-->
<!--                <div>（⩽80）</div>-->
<!--              </div>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="供货价" prop="cost">
              <div style="display: flex;align-items: center;">
                <el-input size="mini" v-model="form.cost" type="number" :max="80"  style="max-width: 220px;"
                        placeholder="请输入让利"></el-input>
              </div>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-row>
              <el-col :span="3">
                <el-form-item label="首页展示">
                  <el-switch size="mini" :active-value="1" :inactive-value="0" v-model="form.is_index"></el-switch>
                </el-form-item>
              </el-col>
<!--              <el-col :span="3">-->
<!--                <el-form-item label="是否可用现金">-->
<!--                  <el-switch size="mini" :active-value="1" :inactive-value="0" v-model="form.is_cash"></el-switch>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
              <el-col :span="3">
                <el-form-item label="推荐展示">
                  <el-switch size="mini" :active-value="1" :inactive-value="0" v-model="form.is_extension"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="热卖展示">
                  <el-switch size="mini" :active-value="1" :inactive-value="0" v-model="form.is_hot"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="上架">
                  <el-switch  size="mini" :active-value="1" :inactive-value="0" v-model="form.state"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品简介" prop="name">
              <el-input type="textarea" rows="3" size="mini" maxlength="42" show-word-limit v-model="form.title"
                placeholder="请输入商品简介"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="展示图片" prop="name">
            <div style="color:red;">建议比例:400/400</div>
              <el-upload class="avatar-uploader" :action="upload + '/'" :show-file-list="false" :data="upimg"
                :on-success="handleAvatarSuccess" :before-upload="beforeupload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="展示视频">
              <div style="color:red;">比例:750/750</div>
              <el-upload :action="upload + '/'" :show-file-list="false" :data="upimg" :on-success="handleAvatarSuccesss"
                :before-upload="beforeuploads">
                <video v-if="videoUrl" :src="videoUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <el-button v-if="videoUrl" type="danger" size="mini" @click="removeVideo" style="margin-top: 10px;">删除视频</el-button>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="轮播图" prop="name">
              <div style="color:red;">比例:750/750</div>
              <el-upload :action="upload + '/'" list-type="picture-card" :on-preview="handlePictureCardPreview"
                :before-upload="beforeAvatarUpload" :on-success="someSuccess" :data="upimg" :limit="4"
                :file-list="filelist" :on-remove="handleRemove">
                <i class="el-icon-plus" style="line-height: 90px;text-align: center;"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible"><img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
              <div>最多上传4张</div>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="商品规格" prop="name">
              <el-collapse v-model="activeName">
                <el-collapse-item title="规格管理(点击展开更多设置)" name="2">
                  <div>
                    <el-button plain @click="addattrubut" size="mini">添加规格</el-button>
                    <el-button plain @click="autoprice" size="mini">一键填写价格</el-button>
                    <el-button plain @click="autostock" size="mini">一键添加库存</el-button>
                    <el-button plain @click="autosupply">一键供货价</el-button>
                    <!-- <el-button plain @click="autopv">一键PV</el-button> -->
  <!--                  <el-button plain @click="autozkfc">一键ZKFC/DL</el-button>-->
                    <!-- <el-button plain @click="addnewattr">新增新规格</el-button> -->
                  </div>
                  <div style="margin-top: 10px;">
                    <el-table :data="attrubutetable" class="table" ref="multipleTable" border size="mini"
                      header-cell-class-name="table-header">
                      <el-table-column prop="type_name" label="规格名称" header-align="center" width="150" align="center">
                        <template slot-scope="scope">
                          <el-select v-model="scope.row.type_name" v-if="attrlist.length > 0" placeholder="请选择规格" size="mini"
                            @change="shooseattr(scope.row)">
                            <el-option v-for="(i, index) in attrlist" :key="index" :label="i.type_name"
                              :value="i.type_name"></el-option>
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column label="规格值" header-align="center">
                        <template slot-scope="scope" v-if="scope.row.index >= 0 && attrlist.length > 0">
                          <el-button plain :class="scope.row.attrindexlist[rowindex] == 1 ? 'activeattr' : ''" size="mini"
                            @click="clickattr(scope.row, rowindex)"
                            v-for="(i, rowindex) in attrlist[attrlist.findIndex(is => is.type_name == scope.row.type_name)].type_attr"
                            :key="rowindex">
                            {{ i.val }} <!--    {{ attrlist.findIndex(is=>is.type_name==scope.row.type_name) }} -->
                          </el-button>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" header-align="center" width="80">
                        <template slot-scope="scope">
                          <el-button size="mini" plain @click="deleteattr(scope.row)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  <!-- 属性价格表 -->
                  <div style="margin-top: 10px;">
                    <el-table :data="attrpricetable" v-if="attrpricetable.length > 0 && attrubutetable.length > 0" border size="mini"
                      class="table" ref="multipleTable" header-cell-class-name="table-header">
                      <el-table-column :prop="i.type_name" :label="i.type_name" v-for="(i, inde) in attrubutetable"
                        :key="inde" header-align="center" min-width="80" align="center">
                        <template slot-scope="scope" v-if="scope.row.attr[inde]">
                          {{ scope.row.attr[inde].val }}
                        </template>
                      </el-table-column>
                      <el-table-column prop="type_name" label="价格" header-align="center" min-width="80" align="center">
                        <template slot-scope="scope">
                          <el-input size="mini" v-model="scope.row.price" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="type_name" label="供货价" header-align="center" min-width="80" align="center">
                        <template slot-scope="scope">
                          <el-input v-model="scope.row.supply" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                        </template>
                      </el-table-column>
                      <!-- <el-table-column prop="type_name" label="PV值" header-align="center" min-width="80" align="center">
                        <template slot-scope="scope">
                          <el-input v-model="scope.row.pv" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                        </template>
                      </el-table-column> -->
  <!--                    <el-table-column prop="type_name" label="ZKFC/DL" header-align="center" min-width="80"-->
  <!--                      align="center">-->
  <!--                      <template slot-scope="scope">-->
  <!--                        <el-input v-model="scope.row.coupon" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>-->
  <!--                      </template>-->
  <!--                    </el-table-column>-->

                      <el-table-column prop="type_name" label="库存" header-align="center" min-width="80" align="center">
                        <template slot-scope="scope">
                          <el-input size="mini" v-model="scope.row.stock" onkeyup="value=value.replace(/[^\d]/g,'')"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="type_name" label="展示图(可选)" header-align="center" min-width="150"
                        align="center">
                        <template slot-scope="scope">
                          <el-upload class="upload-demo" action="http://upload.qiniup.com/" :show-file-list="false"
                            :data="upimg" :objectBind="scope.$index" :before-upload="beforeAvatarUpload"
                            :on-success="handSuccessmore">
                            <img @click="sss(scope.$index)" v-if="form.img || scope.row.img"
                              :src="scope.row.img ? scope.row.img : form.img" style="width: 50px;height: 50px;" />
                            <el-button @click="sss(scope.$index)" v-if="!form.img && !scope.row.img" size="mini"
                              type="primary">点击上传</el-button>
                          </el-upload>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" header-align="center" width="80">
                        <template slot-scope="scope">
                          <el-button size="mini" plain @click="deletpraci(scope.row)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="商品详情" prop="name">

            <my-editor @getContent="getContent" :token="upimg.token" :url="url" :upload="upload" :content="form.details"
              ref="editor"></my-editor>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="onSubmit">表单提交</el-button>
              <el-button @click="back">取消</el-button>
            </el-form-item>
          </el-col>

        </el-form>
      </el-row>
      </div>

    </div>
  </div>
</template>

<script>
import MyEditor from '@/components/MyEditor.vue'
export default {
  name: 'addgoods',
  components: {
    MyEditor
  },
  data() {
    return {
      page: 1,
      optionss: [{ name: '普通', ID: 0 }, { name: '百元区', ID: 1 }, { name: '千元区', ID: 2 }, { name: '万元区', ID: 3 }, { name: '兑换区', ID: 4 }], //分区类型 下拉选项
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
      },
      options: [],
      price: '',
      select: false,
      isselect: false,
      upimg: {
        token: '',
        key: new Date().valueOf()
      },
      upload: '',
      url: '',
      imageUrl: '',
      videoUrl: '',
      thisrow: {},
      images: [],
      showdetails: true,
      activeName: '1',
      navigation_list: [], //分区
      firstlist: [], //分类
      secondlist: [],
      filelist: [],
      thirdlist: [],
      attrlist: [], // 属性列表
      attrubutetable: [], //'属性表'
      attrpricetable: [], //属性价格表
      dialogImageUrl: '',
      baodan: true,
      index: 0,
      dialogVisible: false,
      activeStep: 0, // 当前步骤
      steps: ['商品信息', '规格设置', '详情与提交'], // 步骤条
      form: {
        is_single: 0,
        chickis_single: 0,
        name: '',//商品名称
        img: '',//首页展示图
        details: '',//商品介绍
        class_first_id: '',
        class_second_id: '',
        class_third_id: '',
        business_class_id: 0,
        img_list: [],
        freight: '',
        stock: '',
        sales: 0,
        coupon: 0,
        price: '',
        video: '',
        market: '',
        is_extension: 0,
        is_hot: 0,
        is_index: 0,
        sort: 0,
        partition_id: '',
        title: '',
        attribute_list: [],
        state: 1,
        is_cash: 1,
        cost: 1,//成本价
        virtually_sales: 0,
        platform_discount:0,
        discount:0
      },
      oldfrom: {
        is_single: 0,
        chickis_single: 0,
        name: '',//商品名称
        img: '',//首页展示图
        details: '',//商品介绍
        class_first_id: '',
        class_second_id: '',
        class_third_id: '',
        business_class_id: 0,
        img_list: [],
        freight: '',
        stock: '',
        sales: 0,
        coupon: 0,
        price: '',
        video: '',
        market: '',
        is_extension: 0,
        is_hot: 0,
        is_index: 0,
        sort: 0,
        partition_id: '',
        title: '',
        attribute_list: [],
        state: 1,
        is_cash: 0,
        cost: 1,//成本价
        virtually_sales: 0,
      },
      addstate: true
    };
  },
  activated() {
  },
  watch: {
    // 监听路由对象$route的变化
    '$route': {
      handler: function (to, from) {

        // this.getData()
      },
      // 设置为深度监听
      deep: true
    }
  },
  created() {

  },
  mounted() {
    this.getToken().then(res => {
      this.upimg.token = res.data.token
      this.url = res.data.url
      this.upload = res.data.upload
    },
      function () {
        console.log('请求失败处理');
      }
    )
    this.init()
    try {
      if (this.$route.query.id) {
        console.log("有吗，")
        this.getData()
        this.addstate = false
        this.page = this.$route.query.page
      }
    } catch {

    }
  },
  methods: {
    // 下一步
    nextStep() {
      if (this.activeStep < this.steps.length - 1) {
        this.activeStep++;
      }
    },
    // 上一步
    prevStep() {
      if (this.activeStep > 0) {
        this.activeStep--;
      }
    },
    // 跳转到指定步骤
    jumpToStep(index) {
      if (index >= 0 && index < this.steps.length) {
        this.activeStep = index;
      }
    },
    // 步骤控制方法
    nextStep() {
      if (this.activeStep < 5) {
        this.activeStep++;
      }
    },
    prevStep() {
      if (this.activeStep > 0) {
        this.activeStep--;
      }
    },
    getData() {
      this.request('admin/goodsDetails/', 'post', { id: Number(this.$route.query.id) }).then(res => {

        this.form = res.data
        this.imageUrl = res.data.img
        this.filelist = eval('(' + res.data.img_list + ')').map(item => {//重构轮播
          return {
            name: item,
            url: item
          }
        })
        this.form.img_list = eval('(' + res.data.img_list + ')') //重构轮播
        this.form.class_first_id = res.data.class_first_id
        this.form.partition_id = res.data.partition_id ? res.data.partition_id : ''
        this.form.freight = res.data.freight ? res.data.freight : ''
        this.request('admin/add_attribute/', 'get', { page: 1, size: 100 }).then(ress => {
          this.attrlist = ress.data
          //规格
          let attr = []
          let attrubutetable = []
          //处理商品规格
          res.data.attribute_list[0].attr.forEach((item, index) => {
            attrubutetable[index] = []
          })
          res.data.attribute_list.forEach((item, index) => {

            item.attr.forEach((items, indexs) => {
              let attrlist = this.attrlist.filter(i => {
                return items.attr == i.type_name
              })[0].type_attr.map(k => {
                return k.val
              })
              attrubutetable[indexs] = {
                type_name: items.attr,
                index: this.attrlist.findIndex(is => is.type_name == items.attr),
                attrindexlist: attrlist,
              }
            })
            let attrs = item.attr.map(items => {
              return {
                attr: items.attr,
                val: items.val
              }
            })
            attr.push({
              attr: attrs,
              attrcash_coupon: 0,
              price: item.price,
              coupon: item.coupon,
              img: item.img,
              stock: item.stock,
              pv: item.pv,
              supply: item.supply,
            })
          })
          //处理商品规格
          let list = []
          let lists = []
          attr.forEach((item, index) => {
            list[index] = new Array
            item.attr.forEach((items, indexs) => {
              lists[indexs] = new Array
            })
          })
          attr.forEach((item, index) => {
            item.attr.forEach((items, indexs) => {
              list[index].push(items.val) //= [...list[indexs], items.val]
            })
          })
          for (var k = 0; k < lists.length; k++) {
            list.forEach((item, index) => {
              lists[k].push(item[k]);
            })
          }
          lists.forEach((item, index) => {
            let listbox = []
            attrubutetable[index].attrindexlist.forEach((items, indexs) => {
              listbox.push(items == item[indexs] ? 1 : 0)
            })
            attrubutetable[index].attrindexlist = listbox
          })
          this.attrubutetable = attrubutetable
          this.attrpricetable = attr
          if (res.data.class_first_id > 0) {//获取二级分类
            this.form.class_second_id = res.data.class_second_id != 0 ? res.data.class_second_id : ''
            this.request('admin/secondClass/', 'get', { class_first_id: this.form.class_first_id, page: 1, size: 100, keyword: '' }).then(res => {

              if (res.data.total != 0) {
                this.secondlist = res.data.data
                this.secondlist.unshift({ name: '空', ID: 0 })
              }
            })
          } else {
            this.form.class_second_id = ''
          }
          if (res.data.class_second_id > 0) {//获取三级分类
            this.form.class_third_id = res.data.class_third_id
            this.request('admin/thirdClass/', 'get', { class_second_id: this.form.class_second_id, page: 1, size: 100, keyword: '' }).then(res => {

              if (res.data.total != 0) {
                this.thirdlist = res.data.data
                this.thirdlist.unshift({ name: '空', ID: 0 })
              }
            })
          } else {
            this.form.class_third_id = ''
          }

        })
      })
    },
    //获取初始化
    init() {
      //获取运费模版
      this.request('admin/freightTemplate/', 'get', { page: 1, size: 50 }).then(res => {
        this.options = res.data.data
      })
      //获取一级分类
      this.request('admin/firstClass/', 'get', { page: 1, size: 100, keyword: '' }).then(res => {
        this.firstlist = res.data.data
      })
      //获取所有规格
      if (!this.$route.query.id) {
        this.request('admin/add_attribute/', 'get', { page: 1, size: 100 }).then(res => {
          this.attrlist = res.data
        })
      }
      //获取商品分区
      this.request('admin/partition/', 'get', { page: 1, size: 100 }).then(res => {
        this.navigation_list = res.data.data
        console.log("this.navigation_list", this.navigation_list)
      })
    },

    // 修改商品分区
    changeissing(e) {
      console.log(e)
      this.form.chickis_single = 1
    },
    //获取2级分类
    setfirst(isGet=true) {
      if(isGet){
        this.form.class_second_id = ''
      }
      this.request('admin/secondClass/', 'get', { class_first_id: this.form.class_first_id, page: 1, size: 100, keyword: '' }).then(res => {
        if (res.data.total != 0) {
          this.secondlist = res.data.data
          this.secondlist.unshift({ name: '空', ID: 0 })
        }

      })
    },
    //获取3级分类
    setsecond(isGet=true) {
      if(isGet){
        this.form.class_third_id = ''
      }
      this.request('admin/thirdClass/', 'get', { class_second_id: this.form.class_second_id, page: 1, size: 100, keyword: '' }).then(res => {

        if (res.data.total != 0) {
          this.thirdlist = res.data.data
          this.thirdlist.unshift({ name: '空', ID: 0 })
        }
      })
    },



    getContent(e) {
      this.form.details = e
    },

    // 编辑商品
    sss(s) {
      this.index = s;
    },
    // 删除展示图片
    removeImage() {
      this.imageUrl = '';
      this.form.img = '';
    },
    // 删除展示视频
    removeVideo() {
      this.videoUrl = '';
      this.form.video = '';
      // Reset the upload state
      this.$refs.upload && this.$refs.upload.clearFiles();
    },


    //一键填写价格
    autoprice() {
      console.log(this.form, "form")
      for (var i = 0, len = this.attrpricetable.length; i < len; i++) {
        this.attrpricetable[i].price = this.form.price;
      }
    },


    //一键填写库存
    autostock() {
      for (var i = 0, len = this.attrpricetable.length; i < len; i++) {
        this.attrpricetable[i].stock = this.form.stock;
      }
    },
    //一键填写供货价
    autosupply() {
      for (var i = 0, len = this.attrpricetable.length; i < len; i++) {
        this.attrpricetable[i].supply = this.form.cost;
      }
    },
    //一键填写PV
    autopv() {
      for (var i = 0, len = this.attrpricetable.length; i < len; i++) {
        this.attrpricetable[i].pv = this.form.pv;
      }
    },
    //一键填写ZKFC
    autozkfc() {
      console.log(this.form, "form")

      for (var i = 0, len = this.attrpricetable.length; i < len; i++) {
        this.attrpricetable[i].coupon = this.form.coupon;
      }
    },
    //点击属性按钮
    clickattr(row, index) {
      row.attrindexlist[index] = row.attrindexlist[index] == 1 ? 0 : 1;
      this.attrlist[row.index].type_attr.push(1);
      this.attrlist[row.index].type_attr.pop();
      this.drawtable(); // 改变属性重新绘制绘制表格
    },
    //绘制属性价格表
    drawtable() {
      this.attrpricetable = [];
      let cpa = this.getattrprice(); //组合函数
      for (var k = 0; k < cpa.length; k++) {
        var newarr = [];
        for (var i = 0; i < cpa[k].length; i++) {
          newarr.push({
            attr: this.attrubutetable[i].type_name,
            val: cpa[k][i].val
          });
        }
        this.attrpricetable.push({
          attr: newarr,
          coupon: 0,
          price: '',
          cash_coupon: 0,
          img: '',
          stock: '',
          pv: "",
          supply: 0,
        });
      }
    },
    //添加规格按钮
    addattrubut() {
      this.attrubutetable.push({
        type_name: '请选择属性',
        index: -1
      });
    },
    // 删除规格按钮
    deleteattr(row) {
      this.attrubutetable = this.attrubutetable.filter(t => t.type_name != row.type_name);
      this.drawtable(); // 改变属性重新绘制绘制表格
    },
    // 删除单行属性
    deletpraci(row) {
      this.attrpricetable = this.attrpricetable.filter(t => t != row);
      // console.log(this.attrpricetable)
    },
    addnewattr() {
      // this.$router.push({
      //   path: '/attributelist'
      // });
    },
    //选择属性类别
    shooseattr(row) {
      let index = 0;
      let p = this.attrubutetable.filter(t => t.type_name == row.type_name);
      if (p.length > 1) {
        row.type_name = '';
        return this.$message.error('不能选择相同属性');
      }

      for (var i = 0; i < this.attrlist.length; i++) {
        if (this.attrlist[i].type_name == row.type_name) {
          index = i;
          break;
        }
      }
      for (var i = 0; i < this.attrubutetable.length; i++) {
        if (this.attrubutetable[i].type_name == row.type_name) {
          this.attrubutetable[i].index = index;
          break;
        }
      }
      this.attrubutetable[i].attrindexlist = [];
      this.attrlist[i].type_attr.forEach(f => {
        this.attrubutetable[i].attrindexlist.push(0);
      });
    },


    handlePictureCardPreview(res, file) {
      this.dialogImageUrl = this.url + res.key;
      this.dialogVisible = true;
    },

    handleRemove(res, file) {
      this.filelist = file
      this.form.img_list = file.map(item => {
        return item.url
      })
    },



    async beforeAvatarUpload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'video/mp4') {
        this.$message.error('上传头像图片只能是 JPG、PNG 格式!');
        return false;
      }
      // if (file.size / 1024*1024> 500 && file.type !== 'video/mp4') {
      // 	this.$message.error('上传图标大小不能超过 500k!');
      // 	return false;
      // }
      let types = file.name.split('.')//获取视频格式
      this.upimg.key = this.$name + '/home/' + new Date().valueOf() + '.' + types[types.length - 1];

    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.form.img = this.url + res.key;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeupload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传头像图片只能是 JPG、PNG 格式!');
        return false;
      }
      if (file.size / 1024 / 1024 > 1) {
        this.$message.error('上传图标大小不能超过 1M!');
        return false;
      }
      let types = file.name.split('.')//获取图片格式
      this.upimg.key = this.$template + '/home/' + new Date().valueOf() + '.' + types[types.length - 1];
    },
    // 上传视频
    handleAvatarSuccesss(res, file) {
      this.form.video = this.url + res.key;
      this.videoUrl = URL.createObjectURL(file.raw);
    },
    beforeuploads(file) {
      if (file) {
        if (file.type !== 'video/mp4') {
          this.$message.error('请上传视频格式');
          return false;
        }
        if (file.size / 1024 > 10240) {
          this.$message.error('上传视频大小不能超过 10240k!');
          return false;
        }
      }
      let types = file.name.split('.')//获取视频格式 business
      this.upimg.key = this.$name + '/home/' + new Date().valueOf() + '.' + types[types.length - 1];
    },
    someSuccess(res, file) {
      this.form.img_list.push(this.url + res.key)
      this.filelist.push({
        name: res.key,
        url: this.url + res.key
      })

    },
    handSuccessmore(res, file, files) {
      this.attrpricetable[this.index].img = this.url + res.key;
      this.thisrow.img = this.url + res.key;
    },
    //表单验证
    FormValidation() {
      let data = this.form;
      this.form.attribute_list = []
      this.attrpricetable.forEach(item => {
        item.price = Number(item.price)
        item.stock = Number(item.stock)
        item.pv = Number(item.pv)
        item.coupon = Number(item.coupon)
        item.supply = Number(item.supply)

        if (!item.img) {
          item.img = this.form.img
        }
        this.form.attribute_list.push(item)
      })
      if (!data.name) {
        this.$message.error('请输入商品名称');
        return false;
      }
      if (!data.partition_id > 0) {
        this.$message.error('请选择商品分区');
        return false;
      }
      if (!data.class_first_id > 0) {
        this.$message.error('请选择商品一级分类');
        return false;
      }
      // if (!data.freight) {
      //   this.$message.error('请选择运费模版');
      //   return false;
      // }

      if (!data.title) {
        this.$message.error('请输入商品简介');
        return false;
      }
      if (data.market < 0) {
        this.$message.error('请输入市场价格');
        return false;
      }
      if (!data.price > 0) {
        this.$message.error('请输入商品价格');
        return false;
      }
      if (data.stock < 0) {
        this.$message.error('请输入商品库存');
        return false;
      }

      if (!data.cost > 0) {
        this.$message.error('请输入成本价');
        return false;
      }


      if (!data.img) {
        this.$message.error('请上传商品展示图片');
        return false;
      }
      if (this.filelist.length == 0) {
        this.$message.error('请上传商品轮播图片');
        return false;
      }
      if (this.form.attribute_list.length == 0) {
        this.$message.error('请选择商品规格');
        return false;
      }
      if (this.form.attribute_list.filter(item => item.price > 0).length == 0) {
        this.$message.error('规格价格需大于0');
        return false;
      }
      if (!this.form.details) {
        this.$message.error('请填写商品详情');
        return false;
      }

      return true;
    },
    onSubmit() {
      let that = this
      if (!this.FormValidation()) return;



      let data = JSON.parse(JSON.stringify(this.form))
      data.name = this.form.name,//商品名称
        data.img = this.form.img,//首页展示图
        data.details = this.form.details,//商品介绍
        data.class_first_id = this.form.class_first_id,
        data.class_second_id = this.form.class_second_id > 0 ? this.form.class_second_id : 0,
        data.class_third_id = this.form.class_third_id > 0 ? this.form.class_third_id : 0,
        data.img_list = JSON.stringify(this.form.img_list),
        data.stock = Number(this.form.stock),
        data.sales = Number(this.form.sales),
        data.coupon = Number(this.form.coupon),
        data.pv = Number(this.form.pv),

        data.coupon = Number(this.form.coupon),
        data.price = Number(this.form.price),
        data.video = this.form.video,
        data.market = Number(this.form.market),
        data.is_extension = Number(this.form.is_extension),
        data.is_hot = Number(this.form.is_hot),
        data.is_index = Number(this.form.is_index),
        data.is_cash = Number(this.form.is_cash)
      data.sort = Number(this.form.sort),
        data.partition_id = this.form.partition_id,
        data.title = this.form.title,
        data.attribute_list = this.form.attribute_list
      data.state = Number(this.form.state)
      data.cost = Number(this.form.cost)
      data.integral_send = Number(this.form.integral_send)
      data.nft_card_num = Number(this.form.nft_card_num)
      data.balance_send = Number(this.form.balance_send)
      data.virtually_sales = Number(this.form.virtually_sales)
      data.freight = Number(this.form.freight)
      data.discount = Number(this.form.discount)
      data.platform_discount = Number(this.form.platform_discount)
      if(data.discount > 20) {
        return this.$message.error('返利不能大于30');
      }
      if(data.platform_discount > 80) {
        return this.$message.error('返利不能大于80');

      }
      // if (this.$route.query.id) {
      //   data['id']=this.$route.query.id
      // }
      this.request('admin/add_goods/', this.addstate ? 'post' : 'PUT', data).then(res => {

        if (res.errno == 0) {
          this.$message.success(res.errmsg);
          this.from = JSON.parse(JSON.stringify(this.oldfrom))
          setTimeout(f => {

            that.$router.push({ path: '/commodity/goodslist', query: { page: this.page }, })
            // this.$router.go(-1)
            location.reload();
          }, 500);
        } else {
          this.form.img_list = JSON.parse(JSON.stringify(this.form.img_list)),
            this.$message.error(res.errmsg);
        }
      })

    },
    back() {
      this.from = JSON.parse(JSON.stringify(this.oldfrom))
      setTimeout(() => {
        this.$router.push({ path: '/commodity/goodslist' })
        location.reload();
      }, 500);

    },
    // 工具函数
    doCombination(arr) {
      //排列组合算法
      var count = arr.length - 1;
      var tmp = [];
      var totalArr = [];

      function doCombinationCallback(arr, curr_index) {
        for (var val of arr[curr_index]) {
          tmp[curr_index] = val;
          if (curr_index < count) {
            doCombinationCallback(arr, curr_index + 1);
          } else {
            totalArr.push(tmp);
          }
          var oldTmp = tmp;
          tmp = [];
          for (var index of oldTmp) {
            tmp.push(index);
          }
        }
        return totalArr;
      }
      return doCombinationCallback(arr, 0);
    },

    getattrprice() {
      var arr = [];
      this.attrubutetable.forEach(f => {
        var b = [];
        if (f.index > -1) {
          for (var i = 0; i < f.attrindexlist.length; i++) {
            if (f.attrindexlist[i] == 1) {
              b.push(this.attrlist[f.index].type_attr[i]);
            }
          }
        }
        if (b.length > 0) {
          arr.push(b);
        }
      });
      return arr.length == 0 ? [] : this.doCombination(arr);
    },

  }
};
</script>
<style scoped="scoped">
.activeattr {
  border: 1px solid rgb(64, 158, 255);
  color: rgb(64, 158, 255);
}

.avatar {
  width: 100%;
  height: 100%;
}

.el-upload {
  width: 100px !important;
  height: 100px !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
  border: 1px dashed #c0ccda;
  background-color: #fbfdff;
  border-radius: 6px;
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
/* 使用 /deep/ 或 >>> 来穿透 scoped 样式 */
::v-deep .el-table th.el-table__cell {
  background-color: #f2f2f2;
  /* 设置表头颜色 */
  color: #333;
  /* 设置表头文字颜色 */
}
.el-form-item{
  margin-bottom: 10px;
}
</style>
